﻿using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.WebApi.Utility._MD5;
using MyBlog.WebApi.Utility.ApiResult;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WriterInfoController : Controller
    {
        private readonly IWriterInfoService _iWriterInfoService;
        public WriterInfoController(IWriterInfoService iWriterInfoService)
        {
            this._iWriterInfoService = iWriterInfoService;
        }

        /// <summary>
        /// 获取所有类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetWriterInfos")]
        public async Task<ApiResult> GetWriterInfos()
        {
            var res = await _iWriterInfoService.QueryAsync();
            if (res.Count == 0) return ApiResultHelper.Error("没有更多的人员信息");
            return ApiResultHelper.Success(res);
        }


        [HttpPost("Create")]
        public async Task<ApiResult> Create(WriterInfo writerInfo)
        {
            WriterInfo obj = new WriterInfo()
            {
                Name = writerInfo.Name,
                UserName = writerInfo.UserName,
                UserPwd = MD5Helper.MD5Encrypt32(writerInfo.UserPwd),
            };

            // 验证用户名是否存在
            var user = await _iWriterInfoService.FindAsync( c => c.UserName == writerInfo.UserName);
            if (user!= null) return ApiResultHelper.Error("用户已存在");

            var res = await _iWriterInfoService.CreateAsync(obj);
            if (res == null) return ApiResultHelper.Error("创建失败");
            return ApiResultHelper.Success(res);
        }

        [HttpPut("Update")]
        public async Task<ApiResult> Update(int Id)
        {
            // 验证用户名是否存在
            var user = await _iWriterInfoService.FindAsync(c => c.Id != Id);
            if (user == null) return ApiResultHelper.Error("用户名不存在");

            // user

            //var res = await _iWriterInfoService.EditAsync(writerInfo);
            //if (res == null) return ApiResultHelper.Error("更新失败");
            // return ApiResultHelper.Success(res);

            return ApiResultHelper.Success("更新成功");
        }

        [HttpDelete("Delete/{id}")]
        public async Task<ApiResult> Delete(int id)
        {
            var res = await _iWriterInfoService.DeleteAsync(id);
            if (res == null) return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(res);
        }
    }
}
